package com.mall.b2c.controller;

import com.mall.b2c.service.LuceneService;
import com.mall.common.controller.BaseController;
import com.mall.common.util.ResponseUtils;
import net.sf.json.JSONObject;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.Future;

/**
 * 后台Action类 - lucene
 */
@Controller
@RequestMapping("/admin/b2c/lucene")
public class LuceneController extends BaseController {

    @Resource
    LuceneService luceneService;

    @RequestMapping(value = "/build", method = RequestMethod.GET)
    public String build(Model model) {
        model.addAttribute("defaultBeginDate", DateUtils.addDays(new Date(), -7));
        model.addAttribute("defaultEndDate", DateUtils.addDays(new Date(), 1));
        return "/admin/b2c/lucene/build";
    }

    /**
     * 批量建商品索引
     */
    @RequestMapping(value = "/buildIndex", method = RequestMethod.POST)
    public String buildIndex(Long goodsCategoryId,
                             @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginDate,
                             @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
                             HttpServletResponse response) {
        int buildCount = -1; //-1表示异步未返回
        long beginTimestamp = System.currentTimeMillis();
        try {
           Future<Integer> futureCount =  luceneService.indexGoods(beginDate, endDate, goodsCategoryId);
            if(futureCount.isDone()){
                buildCount = futureCount.get();
            }
        } catch (Exception e) {
            log.error("生成商品索引发生错误!",e);
            return ResponseUtils.renderText("生成商品索引发生错误!", response);
        }
        long endTimestamp = System.currentTimeMillis();
        JSONObject json = new JSONObject();
        json.put("buildCount", buildCount);
        json.put("buildTime", Long.valueOf(endTimestamp - beginTimestamp));
        json.put("isCompleted", true);
        return ResponseUtils.renderJSON(json, response);
    }

}
